//
//  ManageAddressVC.m
//  sensen_ios
//
//  Created by mc on 16/2/25.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ManageAddressVC.h"


#import "NewAddressVC.h"

#import "DetailAddressVC.h"

#import "AddressModel.h"

@interface ManageAddressVC ()<UITableViewDataSource,UITableViewDelegate>{
    UITableView         *  _tableView;
}


@property (nonatomic,strong) NSMutableArray  *  dataArray;
@property (nonatomic,strong) UILabel * lblEmpty;

@end

@implementation ManageAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"地址管理";
    [self initViews];
    
    
    // 创建导航栏左边返回按钮
    [self createLeftBarButtonItemWithImagename:nil];
    
    // Do any additional setup after loading the view.
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
    
    //地址列表
    [self requestAddressList];
    
}

-(void)showEmpty{
    self.lblEmpty.hidden = NO;
    _tableView.hidden = YES;
}
-(void)hideEmpty{
    self.lblEmpty.hidden = YES;
    _tableView.hidden = NO;
}




//初始化View
-(void)initViews{
    
    self.lblEmpty = [[UILabel alloc]init];
    self.lblEmpty.text = @"您还没有添加收货地址\n赶紧添加一个吧!";
    self.lblEmpty.lineBreakMode = NSLineBreakByWordWrapping;
    self.lblEmpty.numberOfLines = 0;
    self.lblEmpty.textColor = [UIColor grayColor];
    self.lblEmpty.textAlignment = NSTextAlignmentCenter;
    
    self.lblEmpty.frame = CGRectMake(0, SCREEN_HEIGHT/3, SCREEN_WIDTH, 80);
    [self.view addSubview:self.lblEmpty];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self buildTableView];
    [self buildAddView];
    
}

-(void)buildTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT- 64 - SCREEN_WIDTH / 8) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.contentInset = UIEdgeInsetsZero;
    _tableView.hidden = YES;
    [self.view addSubview:_tableView];
}

#pragma mark -- TableViewDelegate --

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    AddressModel * model = [self.dataArray objectAtIndex:indexPath.section];
    
    static    NSString  * identifier = @"cell";
    UITableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }

    
    UILabel * nameLable = [[UILabel alloc] init];
    [cell.contentView addSubview:nameLable];
    nameLable.font = FONT(13);
    nameLable.textColor = [UIColor darkGrayColor];
    nameLable.text = model.contactname;
    [nameLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(5);
        make.top.equalTo(cell.contentView).offset(5);
        make.size.mas_equalTo(CGSizeMake(120, 15));
    }];
    
    
    
    UILabel * phoneLable = [[UILabel alloc] init];
    [cell.contentView addSubview:phoneLable];
    phoneLable.text = model.mobile;
    phoneLable.font = FONT(13);
    phoneLable.textColor = [UIColor darkGrayColor];
    phoneLable.textAlignment = NSTextAlignmentRight;
    [phoneLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cell.contentView).offset(-50);
        make.top.equalTo(cell.contentView).offset(5);
        make.size.mas_equalTo(CGSizeMake(120, 15));
    }];
    
    
    
    UILabel * addressLable = [[UILabel alloc] init];
    [cell.contentView addSubview:addressLable];
    addressLable.font = FONT(13);
    addressLable.textColor = [UIColor darkGrayColor];
    [addressLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(nameLable.mas_left).offset(0);
        make.bottom.equalTo(cell.contentView).offset(-5);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 50, 15));
    }];
    addressLable.text = model.address;
    if (model.isDefault) {
        //addressLable.textColor = [UIColor redColor];
        NSString * string = [NSString stringWithFormat:@"【默认】%@", model.address];
        addressLable.attributedText = [string changeText:[UIColor redColor] range:NSMakeRange(0, 4)];
    }
    

    
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
   
    /* 忽略点击效果 */
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
 
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    
   
    AddressModel * model = [self.dataArray objectAtIndex:indexPath.section];
    if (self.delegate) {
        
        [self.delegate didSelectAddress:model];
        [self.navigationController popViewControllerAnimated:YES];
        
    }else{
        
        DetailAddressVC * vc = [[DetailAddressVC alloc] init];
        vc.addressModel = model;
        
        if (indexPath.section == 0) {
            vc.isDefault = YES;
        }else{
            vc.isDefault = NO;
        }
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}




#pragma mark --   添加地址  ---

-(void)buildAddView{
    // 创建退出登录按钮
    UIButton  * addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, _tableView.bottom, SCREEN_WIDTH, SCREEN_WIDTH / 8);
    [self.view addSubview:addBtn];
    [addBtn setTitle:@"添加地址" forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addClick:) forControlEvents:UIControlEventTouchUpInside];
    [addBtn setBackgroundColor:SS_NAVI_BLUE_COLOR];

}

#pragma mark --- 点击添加 --
-(void)addClick:(UIButton *)addBtn{
    NewAddressVC *vc = [[NewAddressVC alloc] init];
    if (self.dataArray.count == 0) {
        vc.isDefault = YES;
    }else{
        vc.isDefault = NO;
    }
    [self.navigationController pushViewController:vc animated:YES];
    
}



#pragma mark  -- 地址列表获取接口  --
-(void) requestAddressList{
    
    
    [SVProgressHUD showWithStatus:@"正在加载...."]; // 请求中
    self.dataArray = [NSMutableArray arrayWithCapacity:1];
    
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    
    [BoyeHttpClient post:@"BY_Address_queryNoPaging" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"___________%@", result);
        if (((NSArray *)result).count == 0 ) {
            [self showEmpty];
            [SVProgressHUD dismiss];
        }else{
            [self hideEmpty];
            for (NSDictionary * dic in (NSArray *)result) {
                AddressModel * model = [[AddressModel  alloc] initContentWithDic:dic];
                model.address_id = [dic[@"id"] integerValue];
                model.isDefault = NO;
                [self.dataArray addObject:model];
            }
            
            [self requestSetDefaultAddress];

        }
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"加载失败，请重试"] withDuration:3];
    }];

    
}

#pragma mark  -- 请求得到默认收货地址  --
-(void) requestSetDefaultAddress{
 
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [BoyeHttpClient post:@"BY_Address_getDefaultAddress" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
          _tableView.hidden = NO;
            int index = 0;
            for (int i = 0; i < self.dataArray.count; i++) {
                AddressModel * model = [self.dataArray objectAtIndex:i];
                model.isDefault = NO;
                if ([result integerValue] == model.address_id) {
                    index = i;
                }
            }
            
    
            AddressModel * model = [self.dataArray objectAtIndex:index];
            model.isDefault = YES;
            if (index != 0) {
                [self.dataArray removeObjectAtIndex:index];
                [self.dataArray insertObject:model atIndex:0];
            }
        
            [_tableView reloadData];
            [SVProgressHUD dismiss];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"加载失败，请重试"] withDuration:3];
        }];
    
    
        
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
